package com.gege;

import java.util.concurrent.*;

/**
 * 使用 CompletionService 提交任务
 *
 * @author gechenpeng
 * @date 2021-04-12
 */
public class Demo3 {

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = new ThreadPoolExecutor(5, 5,
                1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1024),
                new ThreadPoolExecutor.CallerRunsPolicy());

        CompletionService<String> completionService = new ExecutorCompletionService<>(executorService);

        long start = System.currentTimeMillis();

        completionService.submit(() -> execute());

        // 如果完成队列中没有数据, 则阻塞; 否则返回队列中的数据
        Future<String> future = completionService.take();

        executorService.shutdown();

        String message = future.get();

        System.out.println("线程运行的结果是: " + message + ", 耗时: " +
                (System.currentTimeMillis() - start) + " ms");
    }

    private static String execute() throws Exception {
        Thread.sleep(5000);
        return "ok";
    }
}
